/*
 * Copyright (c) 2020 Nanjing Xiaoxiongpai Intelligent Technology Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "cmsis_os2.h"
#include "ohos_init.h"
#include "los_task.h"

#include "los_memory.h"

#define TEST_POOL_SIZE (8*1024)
#define MEMBOX_WR_TEST_NUM  828

__attribute__((aligned(4))) UINT8 g_testDynPool[TEST_POOL_SIZE];

// 打印内存链表标记位
void print_bitmap(struct OsMemPoolHead *ptr)
{
    char i;
    printf("----------------------list bitmap-----------------------\n");
    for(i=0; i<7; i++){
        printf("0x%08x ", ptr->freeListBitmap[i]);
    }
    printf("\n------------------------------------------------------\n");
}

VOID memory_entry(VOID)
{
    UINT32 *mem1 = NULL, *mem2 = NULL;
    UINT32 ret;
    LOS_MEM_POOL_STATUS poolStatus;

    // 初始化内存池
    ret = LOS_MemInit(g_testDynPool, TEST_POOL_SIZE);
    if (LOS_OK  == ret) { printf("Mem init success!\n"); }
    else { printf("Mem init failed!\n"); return; }
    // 打印内存链表标记位图
    print_bitmap((struct OsMemPoolHead *)g_testDynPool);
    // 打印内存池信息
    LOS_MemPoolList();

    // 申请4096大小的内存块
    mem1 = (UINT32 *)LOS_MemAlloc(g_testDynPool, 4096);
    if (mem1 == NULL) { printf("Mem alloc failed!\n"); return;}
    printf("Mem1 alloc success!\n");
    print_bitmap((struct OsMemPoolHead *)g_testDynPool);
    // 打印内存池信息
    LOS_MemPoolList();
    // 申请580字节的内存
    mem2 = (UINT32 *)LOS_MemAlloc(g_testDynPool, 580);
    if (mem2 == NULL) { printf("Mem alloc failed!\n"); return; }
    printf("Mem2 alloc success!\n");
    print_bitmap((struct OsMemPoolHead *)g_testDynPool);
    // 打印内存池信息
    LOS_MemPoolList();
    
    // 内存地址读写验证
    *mem1 = 123;
    printf(" mem1 addr %x, *mem1 = %d\n", mem1, *mem1);
    
    // 释放内存1
    ret = LOS_MemFree(g_testDynPool, mem1);
    if (LOS_OK == ret) { printf("Mem free success!\n"); } 
    else { printf("Mem free failed!\n"); }
    print_bitmap((struct OsMemPoolHead *)g_testDynPool);
    LOS_MemPoolList();
    // 释放内存2
    ret = LOS_MemFree(g_testDynPool, mem2);
    if (LOS_OK == ret) { printf("Mem free success!\n");} 
    else { printf("Mem free failed!\n"); }
    print_bitmap((struct OsMemPoolHead *)g_testDynPool);
    LOS_MemPoolList();

    return;
}


//APP_FEATURE_INIT(interrupt_entry);